<?php
namespace MyAdmin\Controller;

use Think\Controller;

class ProductsController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function index()
  {
    $page = I("page", 1);
    $page_size = I("page_size", 10);
    $model=M("products");
    //查询
    $name = trim(I("name"));
    $shop_name = trim(I("shop_name"));

    //上架
    $where = "s.app_id={$this->app_id} ";
    if ($name) {//用户名
      $where .= " and p.name like '%".trim($name)."%'";
      $where_ar['name']=$name;
      $this->assign("name", $name); 
    }

    if ($shop_name) {//店铺名
      $where .= " and s.name like '%".trim($shop_name)."%'";
      $where_ar['shop_name']=$shop_name;
      $this->assign("shop_name", $shop_name);
    }

    $field = "p.*,s.name as shop_name,pc.name as product_cate_name";
    $order = "p.id desc";
    $list = $model->alias("p")->join("left join ".C("DB_PREFIX")."shops s on s.id=p.shop_id")
    ->join("left join ".C("DB_PREFIX")."product_cates pc on pc.id=p.product_cate_id")
    ->field($field)->where($where)->order($order)->page($page.",".$page_size)->select();
    foreach ($list as $key => &$value) {
      $id = $value['id'];
      $value['created_at'] = local_time($value['created_at']);

      switch ($value['status']) {
        case 1:
          $value['status_str'] = "上架";
          break;
        case 2:
          $value['status_str'] = "回收站";
          break;
        default:
          $value['status_str'] = "下架";
          break;
      }

      $field = "id,price,name,stock";
      $spec_list = M("specs")->field($field)->where("product_id=".$id)->order("id asc")->select();

      $strs = ''; $price = 0;
      foreach ($spec_list as $key2 => $value2) {
        $price +=(int)$value2['stock'];
        $strs.="<tr><td>".$value2['name']."</td>";
        $strs.="<td>".$value2['price']."</td>";
        $strs.="<td>".$value2['stock']."</td></tr>";
      }
      if($strs){
        $list[$key]['product_num']= $price;
      }
      $value['spec'] = $strs;
      $value['name'] = sub_str($value['name'], 15);
    }

    $num = $model->alias("p")->join("left join ".C("DB_PREFIX")."shops s on s.id=p.shop_id")
    ->join("left join ".C("DB_PREFIX")."product_cates pc on pc.id=p.product_cate_id")->where($where)->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $num, $where_ar);
    $this->assign("page_list", $page_list);

    // print_r($page_list);exit;

    $this->display();
  }
  public function plat_index()
  {
    $page = I("page", 1);
    $page_size = I("page_size", 10);
    $model=M("products");
    //查询
    $name = trim(I("name"));

    //上架
    $where = "p.app_id={$this->app_id} and p.is_platform=1 and p.pf_id = 0 ";
    if ($name) {//用户名
      $where .= "and p.name like '%".trim($name)."%'";
      $where_ar['name']=$name;
      $this->assign("name", $name);
    }

    $field = "p.*,pc.name as product_cate_name";
    $order = "p.id desc";
    $list = $model->alias("p")
    ->join("left join ".C("DB_PREFIX")."product_cates pc on pc.id=p.product_cate_id")
    ->field($field)->where($where)->order($order)->page($page.",".$page_size)->select();
    foreach ($list as $key => &$value) {
      if($list[$key]['limit_depot']){
        $list[$key]['limit_depot'] = date('Y-m-d H:i',$list[$key]['limit_depot']);
      }else{
        $list[$key]['limit_depot'] = '不限时';
      }

      $id = $value['id'];
      $value['created_at'] = local_time($value['created_at']);

      switch ($value['status']) {
        case 1:
          $value['status_str'] = "上架";
          break;
        case 2:
          $value['status_str'] = "回收站";
          break;
        default:
          $value['status_str'] = "下架";
          break;
      }

      $field = "id,price,name";
      $spec_list = M("specs")->field($field)->where("product_id=".$id)->order("id asc")->select();

      $strs = '';
      foreach ($spec_list as $key2 => $value2) {
        $strs.="<tr><td>".$value2['name']."</td>";
        $strs.="<td>".$value2['price']."</td></tr>";
      }

      $value['spec'] = $strs;
      $value['name'] = sub_str($value['name'], 15);
    }

    $num = $model->alias("p")->join("left join ".C("DB_PREFIX")."shops s on s.id=p.shop_id")
    ->join("left join ".C("DB_PREFIX")."product_cates pc on pc.id=p.product_cate_id")->where($where)->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $num, $where_ar);
    $this->assign("page_list", $page_list);

    // print_r($page_list);exit;

    $this->display();
  }

  public function update()
  {
    if ($_FILES) {
      $files = file_upload($this->app_id);
      if ($files) {
        $url = $files[0];
        echo json_encode(array('code'=>'success','url' =>$url));
      }else{
        echo json_encode(array('code'=>'success','msg' =>'存储配置错误'));
      }
    }
    // $upload = new \Think\Upload();  // 实例化上传类
    // $upload->maxSize   =102004;  // 设置附件上传大小
    // $upload->exts      =array('jpg', 'gif', 'png', 'jpeg');  // 设置附件上传类型
    // $upload->rootPath  ='./Public/goods/';   // 设置附件上传根目录
    // $upload->subName ='';
    // $info =$upload->upload();
    // if(!$info) {
    //     $info =json_encode(array('code'=>'error','msg'=>$upload->getError()));
    //     echo $info;
    // }else{
    //   // echo json_encode(array('location' => $filetowrite));
    //   echo json_encode(array('code'=>'success','url' =>$info['file']['savename']));
    // }
  }

  public function plat_new_product()
  {
    $product_cates = M("product_cates")->where("app_id={$this->app_id} and status=1")->order("orderby desc")->select();

    $this->assign("product_cates", $product_cates);
    $this->display();
  }

  public function plat_create_product()
  {
    $data = I('post.');
    $model = M("products");

    !$data['logo'] && $data['logo'] = 'http://wdds-app.b0.upaiyun.com/default/logo.jpg';
    $specs = $data['specs'];

    //验证合法性
    if (!$data['name']) {
      $this->error('操作失败, 请输入有效名称');
    }
    if (!isset($data['stock'])) {
      $data['stock'] = 999;
    }
    if (empty($data['product_cate_id'])) {
      $this->error('操作失败, 请选择商品分类');
    }
    // if(!$data['title']) return_data("error",$this->this_table.".title.blank");
    // if(!isset($data['sales'])) return_data("error",$this->this_table.".sales.blank");
    // if(!isset($data['is_related'])) return_data("error",$this->this_table.".is_related.blank");

    //product_cate_id 分类合法性检查，对应商户添加对应类
    $map = array(
      'app_id' => $this->app_id,
      'id' => $data['product_cate_id']);
    $is_have_id = M("product_cates")->where($map)->getField("id");
    if (!$is_have_id) {
      $this->error('操作失败, 请选择商品分类');
    }

    //商品重名检查
    $product_id = $model->where("app_id={$this->app_id} and name='{$data[name]}' and status < 2")->getField('id');
    if ($product_id) {
      $this->error('操作失败, 商品名重复');
    }

    $data['created_at'] = $data['updated_at'] = $data['update_at'] = $this->now_time;
    $data['is_platform'] = 1;
    $data['app_id'] = $this->app_id;

    $data['limit_depot'] = strtotime(trim(I("limit_depot")));
    $model->create($data);
    $id = $model->add();
    if (empty($id)) {
      $this->error('操作失败');
    } else {
      //商品表price存储spec最低价格，修改时同步；
      $littlest_price = $specs_list[0]['price'];
      //规格新增 specs
      if ($specs) {
        $len = 0;
        $prices = array();
        foreach ($specs as $key => $value) {
          if ($value['name']) {
            $specs_list[$len]['name'] = $value['name'];
            $specs_list[$len]['price'] = $value['price'];
            $specs_list[$len]['product_id'] = $id;
            $specs_list[$len]['created_at'] = $this->current_time;
            $len++;

            array_push($prices, $value['price']);
          }
        }
        if ($len > 0) {
          M("specs")->addAll($specs_list);
        }

        //商品表price存储spec最低价格，修改时同步；
        if ($prices) {
          $index = array_search(min($prices), $prices);
          M("products")->where("id=$id")->save(array('price' => $prices[$index]));
        }
      }

      if ($data['photos']) {
        $photo_list = [];
        foreach ($data['photos'] as $photo) {
          $photo_list[] = ['image' => $photo, 'photoable_type' => 'Product', 'photoable_id' => $id];
        }
        $photo_model = M('photos');
        $photo_model->addAll($photo_list);
      }

      $this->success('操作成功', U('Products/plat_index'));
    }
  }

  public function plat_edit_product()
  {
    $id = I("id", '');
    $product = M('products')->where("id=$id")->find();
    $photo_result = M('photos')->field('image')->where(['photoable_id' => $id])->select();
    $photo_list = [];
    if ($photo_result) {
      foreach ($photo_result as $result) {
        $photo_list[] = $result['image'];
      }
    }
    $product['photos'] = $photo_list;
    if($product['limit_depot']){
      $product['limit_depot'] = date('Y-m-d H:i',$product['limit_depot']);
    }

    $this->assign('product', $product);
    $product_cates = M("product_cates")->where("app_id={$this->app_id} and status=1")->order("orderby desc")->select();

    $this->assign("product_cates", $product_cates);

    $this->display();
  }

  public function plat_update_product()
  {
    $data = I('post.');
    $model = M("products");
    !$data['photos'] && $data['photos'] = [];

    $specs = $data['specs'];

    //验证合法性
    if (!$data['name']) {
      $this->error('操作失败, 请输入有效名称');
    }
    if (!isset($data['stock'])) {
      $data['stock'] = 999;
    }
    if (empty($data['product_cate_id'])) {
      $this->error('操作失败, 请选择商品分类');
    }
    // if(!$data['title']) return_data("error",$this->this_table.".title.blank");
    // if(!isset($data['sales'])) return_data("error",$this->this_table.".sales.blank");
    // if(!isset($data['is_related'])) return_data("error",$this->this_table.".is_related.blank");

    //product_cate_id 分类合法性检查，对应商户添加对应类
    $map = array(
      'app_id' => $this->app_id,
      'id' => $data['product_cate_id']);
    $is_have_id = M("product_cates")->where($map)->getField("id");
    if (!$is_have_id) {
      $this->error('操作失败, 请选择商品分类');
    }

    //商品重名检查
    $product_id = $model->where("app_id={$this->app_id} and name='{$data[name]}' and status < 2 and id!={$data['id']} and pf_id = 0")->getField('id');
    if ($product_id) {
      $this->error('操作失败, 商品名重复');
    }

    $data['updated_at'] = $data['update_at'] = $this->now_time;
    $data['is_platform'] = 1;
    $data['app_id'] = $this->app_id;
    $data['limit_depot'] = strtotime(trim(I("limit_depot")));

    $reuslt = $model->where("id={$data['id']}")->save($data);
    if (!$reuslt) {
      $this->error('操作失败');
    } else {
      if ($data['photos']) {
        $count = M('photos')->where("photoable_id={$data['id']}")->count();
        if ($count) {
          M('photos')->where("photoable_id={$data['id']}")->delete();
        }
        $photo_list = [];
        foreach ($data['photos'] as $photo) {
          $photo_list[] = ['image' => $photo, 'photoable_type' => 'Product', 'photoable_id' => $data['id']];
        }
        $photo_model = M('photos');
        $photo_model->addAll($photo_list);
      }
      $this->success('操作成功', U('Products/plat_index'));
    }
  }


  //改变状态
  public function change_status()
  {
    $model = M("products");
    $status = I("status", 2);
    $id = I("id", '');

    $post_data["status"] = $status;
    $post_data["updated_at"] = $this->now_time;
    $where = " id=".$id;

    $list = $model->where($where)->find();
    if($list['product_num'] <=0 && $status == 1)
    {
      $this->error('库存为空，无法上架');
    }

    $result = $model->where($where)->save($post_data);
    if ($result) {
      $this->success('操作成功');
    } else {
      $this->error('操作失败');
    }
  }

  public function plat_cate_index()
  {
    $page = I("page", 1);
    $page_size = I("page_size", 10);
    $model = M("product_cates");
    //查询
    $name = trim(I("name"));

    //上架
    $where = "app_id={$this->app_id}";
    if ($name) {//用户名
      $where .= " and name like '%".trim($name)."%'";
      $where_ar['name']=$name;
      $this->assign("name", $name);
    }

    $field = "*";
    $order = "id desc";
    $list = $model
    ->field($field)->where($where)->order($order)->page($page.",".$page_size)->select();
    foreach ($list as $key => &$value) {
      $id = $value['id'];
      $value['created_at'] = local_time($value['created_at']);

      switch ($value['status']) {
        case 1:
          $value['status_str'] = "开启";
          break;
        case 2:
          $value['status_str'] = "回收站";
          break;
        default:
          $value['status_str'] = "关闭";
          break;
      }
    }

    $num = $model->where($where)->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $num, $where_ar);
    $this->assign("page_list", $page_list);

    // print_r($page_list);exit;

    $this->display();
  }

  public function plat_create_cate()
  {
    $data = I('post.');

    if (!$data['name']) {
      $this->error('操作失败, 请输入有效名称');
    }
    //查重同个商户 分类名唯一
    //允许删除分类后再创建即允许同名 12.18
    $cate_id = M('product_cates')->where("app_id={$this->app_id} and name='$data[name]' and status=1")->getField('id');
    if ($cate_id) {
      $this->error('操作失败,存在同名分类');
    }
    $data['app_id'] = $this->app_id;
    $data['created_at'] = $data['updated_at'] = $this->now_time;
    M('product_cates')->create($data);
    $id = M('product_cates')->add();

    if (empty($id)) {
      $this->error('操作失败');
    } else {
      $this->success('操作成功', U('Products/plat_cate_index'));
    }
  }

  public function plat_edit_cate()
  {
    $id = I("id", '');
    $cate = M('product_cates')->where("id=$id")->find();
    $this->assign('product_cate', $cate);

    $this->display();
  }

  public function plat_update_cate()
  {
    $data = I('post.');

    if (!$data['name']) {
      $this->error('操作失败, 请输入有效名称');
    }
    //查重同个商户 分类名唯一
    //允许删除分类后再创建即允许同名 12.18
    $cate_id = M('product_cates')->where("app_id={$this->app_id} and name='$data[name]' and status=1 and id != {$data['id']}")->getField('id');
    if ($cate_id) {
      $this->error('操作失败,存在同名分类');
    }
    $data['updated_at'] = $this->current_time;
    $result = M('product_cates')->where("id={$data['id']}")->save($data);

    if (!$result) {
      $this->error('操作失败');
    } else {
      $this->success('操作成功', U('Products/plat_cate_index'));
    }
  }

  //改变状态
  public function change_cate_status()
  {
    $model = M("product_cates");
    $status = I("status", 2);
    $id = I("id", '');

    $post_data["status"] = $status;
    $post_data["updated_at"] = $this->now_time;
    $where = " id=".$id;

    $result = $model->where($where)->save($post_data);
    if ($result) {
      $this->success('操作成功', U('Products/plat_cate_index'));
    } else {
      $this->error('操作失败');
    }
  }
}
